package demo3;

import java.util.Arrays;

public class PriorityQueue {
    public int[] elem;
    public int usedSize;
 
    public PriorityQueue() {
        this.elem = new int[10];
    }
 
    /**
     * 建堆的时间复杂度：O(n)
     *
     * @param array
     */
    public void createHeap(int[] array) {
        for (int i = 0; i < array.length; i++) {
            this.elem[i] = array[i];
            usedSize++;
        }
        for (int parent = (elem.length - 1 - 1) / 2; parent >= 0; parent--) {
            shiftDown(parent,elem.length - 1);
        }
    }
 
    /**
     *
     * @param root 是每棵子树的根节点的下标
     * @param len  是每棵子树调整结束的结束条件
     * 向下调整的时间复杂度：O(logn)
     */
    private void shiftDown(int root,int len) {
        int child = root * 2 + 1;
        while (child <= len) {
            if ((child + 1 <= len) && (this.elem[child + 1] > this.elem[child])) {
                child++;
            }
            if (this.elem[root] < this.elem[child]) {
                swap(root,child);
                root = child;
                child = root * 2 + 1;
            } else {
                break;
            }
        }
    }
 
 
    /**
     * 入队：仍然要保持是大根堆
     * @param val
     */
    public void push(int val) {
        if (isFull()) {
            this.elem = Arrays.copyOf(this.elem,this.elem.length * 2);
        }
        this.elem[usedSize++] = val;
        shiftUp(usedSize - 1);
    }
 
    private void shiftUp(int child) {
        int parent = (child - 1) / 2;
        while (child > 0) {
            if (this.elem[parent] < this.elem[child]) {
                swap(parent,child);
                child = parent;
                parent = (child - 1) / 2;
            } else {
                break;
            }
        }
    }
 
    public boolean isFull() {
        return this.usedSize == this.elem.length;
    }

 
    /**
     * 出队【删除】：每次删除的都是优先级高的元素
     * 仍然要保持是大根堆
     */
    public void pollHeap() {
        swap(0,usedSize - 1);
        usedSize--;
        shiftDown(0,usedSize - 1);
    }
 
    public boolean isEmpty() {
        return this.usedSize == 0;
    }
 
    /**
     * 获取堆顶元素
     * @return
     */
    public int peekHeap() {
        //如果为空就返回-1
        if (isEmpty()) {
            return -1;
        }
        return this.elem[0];
    }
    //交换
    public void swap(int x, int y) {
        int temp = this.elem[x];
        this.elem[x] = this.elem[y];
        this.elem[y] = temp;
    }
}